package com.wt.springsamples.handler;

import com.alibaba.fastjson.JSON;
import com.wt.springsamples.common.ApiResult;
import com.wt.springsamples.common.ApiResultCodeEnum;
import com.wt.springsamples.common.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 不能拦截Exception类型异常，会导致Spring Security的异常处理失效
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 指定处理什么异常
     * @param e
     * @return
     */
//    @ExceptionHandler(Exception.class)
//    public ApiResult error(Exception e){
//        log.error(e.getMessage());
//        e.printStackTrace();
//        return ApiResult.fail(e.getMessage());
//    }

    /**
     *   会转发到/error,由spring boot 提供的BasicErrorController处理
     *  自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(BizException.class)
    public void error(HttpServletResponse response, BizException e) throws IOException {
        log.error(e.getMessage());
        e.printStackTrace();

        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        //输出结果
        ApiResult result = ApiResult.build(e.getCode(),e.getMsg());
        response.getWriter().write(JSON.toJSONString(result));
    }

}
